<?php

namespace App\Models\Common;

use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class OperateLogModel extends BaseModel
{
    use KfUid, KfSoftDeletes;

    protected $table = "operate_logs";

    protected $fillable = [
        'business',
        'businessId',
        'userId',
        'userName',
        'logName',
        'logContent',
        'logId',
        'status',

        'isDeleted',
        'createdAt',
        'createdByUid',
        'updatedAt',
        'updatedByUid',
    ];

    const STATUS_OK   = 1; // 已完成
    const STATUS_WAIT = 0; // 待处理

    const BUSINESS_RECTIFY_DETAIL = 'rectify_detail'; // 整改单详情
    const BUSINESS_AGAINST_DETAIL = 'against_detail'; // 违约函详情
    const BUSINESS_APPRAISE = 'appraise'; // 评价反馈
    const BUSINESS_OPEN_SHOP_PREPARATION = 'openShopPreparation'; // 开店-筹备阶段日志
    const BUSINESS_WEB_ALBUM_BATCH_OPERATE = 'web_album_batchOperate'; // 后台运营相册的批量删除、回收站功能
    const BUSINESS_BUSINESS_CIRCLE_RECORD = 'businessCircleRecord';  // 商圈记录
    const BUSINESS_INTENDED_SITE_LOCATION = 'intendedSiteLocationRecord';  // 意向址记录

    public static function add(
        string $business,
        int $businessId,
        int $logId,
        string $logName,
        string $logContent,
        int $status,
        int $userId,
        string $userName = ''
    ) {
        if (!$userName) {
            $userName = (new RmsUserApi())->getUserInfoByIds([$userId], ['username'])['data'][0]['username'] ?? '';
        }

        return self::query()->create([
            'business'   => $business,
            'businessId' => $businessId,
            'userId'     => $userId,
            'userName'   => $userName,
            'logId'      => $logId,
            'logName'    => $logName,
            'logContent' => $logContent,
            'status'     => $status,
        ]);
    }

    public static function edit(string $business, int $businessId, string $logName, string $logContent): int
    {
        $id = self::query()
                  ->where('business', $business)
                  ->where('businessId', $businessId)
                  ->where('status', self::STATUS_WAIT)
                  ->orderByDesc('id')
                  ->value('id');

        return self::query()->where('id', $id)->update([
            'logName'    => $logName,
            'logContent' => $logContent,
            'status'     => self::STATUS_OK,
            'createdAt'  => time(),
        ]);
    }

    public static function getData(string $business, int $businessId, int $logId = 0, string $order = 'asc', $limit = 0)
    {
        return self::query()
                    ->when(
                        in_array($business, [self::BUSINESS_OPEN_SHOP_PREPARATION]), function ($query) {
                        $query->with('resourcesRel');
                    }
                    )
                   ->where('business', $business)
                   ->where('businessId', $businessId)
                   ->when($logId > 0, function ($query) use ($logId) {
                       $query->where('logId', $logId);
                   })
                   ->orderBy('createdAt', $order)
                   ->when($limit > 0, function ($query) use ($limit) {
                       $query->limit($limit);
                   })
                   ->get();
    }

    private array $params;

    /**
     * 设置参数
     * @return $this
     */
    public function setParam(
        string $business,
        int $businessId,
        int $logId,
        string $logName,
        string $logContent,
        int $status,
        int $userId,
        string $userName = '',
        int $currentUid = 0
    ): self {

        if (!$userName) {
            $userName = Cache::store('array')->remember("OperateLogModelUserInfo:{$userId}", 100, function () use ($userId) {
                return (new RmsUserApi())->getUserInfoByIds([$userId], ['username'])['data'][0]['username'] ?? '';
            });
        }

        $this->params[] = [
            'business'   => $business,
            'businessId' => $businessId,
            'userId'     => $userId,
            'userName'   => $userName,
            'logId'      => $logId,
            'logName'    => $logName,
            'logContent' => $logContent,
            'status'     => $status,
            'createdAt'  => time(),
            'updatedAt'  => time(),
            'createdByUid' => $currentUid,
            'updatedByUid' => $currentUid,
        ];

        return $this;
    }

    /**
     * 批量插入
     * @return bool
     */
    public function addBatch(): bool
    {
        return self::query()->insert($this->params);
    }

    /**
     * 关联资源表
     * @return HasMany
     */
    public function resourcesRel(): HasMany
    {
        return $this->hasMany(ResourcesModel::class, 'businessId', 'id')
            ->where('module', ResourcesModel::MODULE_TYPE_OPEN_SHOP)
            ->where('business', ResourcesModel::BUSINESS_OPEN_SHOP_PREPARATION)
            ->where('name', 'LogImg');
    }

    /**
     * 关联资源表
     * @return HasMany
     */
    public function resourcesBusinessCircleRel(): HasMany
    {
        return $this->hasMany(
            ResourcesModel::class, 'businessId', 'id')
            ->where('module', ResourcesModel::MODULE_TYPE_BUSINESS_CIRCLE_RECORD)
            ->where('business', ResourcesModel::BUSINESS_BUSINESS_CIRCLE_RECORD);
    }

    /**
     * 关联资源表
     * @return HasMany
     */
    public function resourcesIntendedSiteLocationRel(): HasMany
    {
        return $this->hasMany(
            ResourcesModel::class, 'businessId', 'id')
            ->where('module', ResourcesModel::MODULE_TYPE_INTENDED_SITE_LOCATION)
            ->where('business', ResourcesModel::BUSINESS_INTENDED_SITE_LOCATION);
    }
}
